1649C - Weird Sum - CodeForces Solution


brute force implementation math matrices *1400

Please click on ads to support us..

Python Code:

d={};i=0
for s in[*open(0)][1:]:
 i+=1;j=0
 for x in s.split():j+=1;a,b=d.setdefault(x,([],[]));a+=i,;b+=j,
print(sum(j*(2*i-len(l)+1)for x in d for l in d[x]for i,j in enumerate(sorted(l))))

C++ Code:

#include <bits/stdc++.h>
#define int long long
using namespace std;

int32_t main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int n,m,x;
    cin >> n >> m;

    map<int, vector< int > >  a;
    map<int, vector< int > >  b;

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cin >> x;
            a[x].push_back(i);
            b[x].push_back(j);
        }
    }

    map<int, vector< int > > :: iterator i;

    for (i = a.begin(); i != a.end(); i++)
    {
        sort(i->second.begin(),i->second.end());
    }
        for (i = b.begin(); i != b.end(); i++)
    {
        sort(i->second.begin(),i->second.end());
    }

    int l,s1=0,s2=0;

    for (i = a.begin(); i != a.end(); i++)
    {
        l=i->first;
        for (int j = 0; j< a[l].size()-1 ; j++)
        {
            s1+= (a[l][j+1] - a[l][j])*(j+1)*(a[l].size()-1-j);
        }
    }
    for (i = b.begin(); i != b.end(); i++)
    {
        l=i->first;
        for (int j = 0; j< b[l].size()-1 ; j++)
        {
            s2+= (b[l][j+1] - b[l][j])*(j+1)*(b[l].size()-1-j);
        }
    }

    cout<<s1+s2<<endl;
}

 				   		 					  	    		     	


Comments

Submit
0 Comments
More Questions

1355A - Sequence with Digits
977B - Two-gram
993A - Two Squares
1659D - Reverse Sort Sum
1659A - Red Versus Blue
1659B - Bit Flipping
1480B - The Great Hero
1519B - The Cake Is a Lie
1659C - Line Empire
515A - Drazil and Date
1084B - Kvass and the Fair Nut
1101A - Minimum Integer
985D - Sand Fortress
1279A - New Year Garland
1279B - Verse For Santa
202A - LLPS
978A - Remove Duplicates
1304A - Two Rabbits
225A - Dice Tower
1660D - Maximum Product Strikes Back
1513A - Array and Peaks
1251B - Binary Palindromes
768B - Code For 1
363B - Fence
991B - Getting an A
246A - Buggy Sorting
884A - Book Reading
1180A - Alex and a Rhombus
445A - DZY Loves Chessboard
1372A - Omkar and Completion